package logic

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"
	"gitee.com/Cauchy_AQ/vxopen/model/redis"
	"gitee.com/Cauchy_AQ/vxopen/pkg/jwt"
	"gitee.com/Cauchy_AQ/vxopen/rpc/wechat/wechat"
	redisv9 "github.com/redis/go-redis/v9"

	"gitee.com/Cauchy_AQ/vxopen/rpc/wechat/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HeartbeatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHeartbeatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HeartbeatLogic {
	return &HeartbeatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HeartbeatLogic) Heartbeat(in *wechat.HeartbeatReq) (*wechat.HeartbeatResp, error) {
	key := redis.CacheQrcodeTicketPrefix + in.Ticket
	openid, err := l.svcCtx.RDB.Get(context.Background(), key).Result()
	if err != nil && err != redisv9.Nil {
		return nil, err
	}
	if err == redisv9.Nil {
		return &wechat.HeartbeatResp{
			Status: false,
			Msg:    "没有查询到用户信息",
		}, nil
	}

	if len(openid) > 0 {
		mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)
		user, err := mongoClient.UserCol.FindOneByOpenId(context.Background(), openid)
		if err != nil {
			return nil, err
		}
		if user != nil {
			aToken, rToken, err := jwt.GenToken(user.Name, user.Mobile, user.OpenID, user.Role.Name)
			if err != nil {
				return nil, err
			}
			return &wechat.HeartbeatResp{
				Status:       true,
				Msg:          "成功查询用户信息",
				AccessToken:  aToken,
				RefreshToken: rToken,
			}, nil
		}
	}
	return &wechat.HeartbeatResp{
		Status: false,
		Msg:    "未知错误",
	}, nil
}
